package org.liukai.ems.controller;

import org.apache.commons.lang3.StringUtils;
import org.liukai.ems.entity.po.User;
import org.liukai.ems.entity.po.UserLoginLog;
import org.liukai.ems.entity.vo.LoginLogVO;
import org.liukai.ems.service.UserLoginLogService;
import org.liukai.ems.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserLoginLogService userLoginLogService;

    //登录
    @RequestMapping("/login")
    public ModelAndView login(User user, HttpServletRequest request) {
        User u = userService.queryUserByUserName(user.getUserName());
        ModelAndView model = new ModelAndView("user/login");
        //model.addObject("user", user);
        if(null == u) {
            model.addObject("msg", "用户不存在");
            return model;
        } else if(!u.getPass().equals(user.getPass())) {
            model.addObject("msg", "密码错误");
            return model;
        }
        HttpSession session = request.getSession();
        UserLoginLog userLoginLog = new UserLoginLog();
        String remoteAddr = getIpAddress(request);
        userLoginLog.setLoginIp(remoteAddr);
        userLoginLog.setLoginTime(new Date());
        userLoginLog.setUserId(u.getUserId());
        userLoginLogService.addUserLoginLog(userLoginLog);
        u.setLastLoginTime(new Date());
        userService.updateUser(u);
        session.setAttribute("currentUser", u);

        model = new ModelAndView("redirect:/user/userList");
        return model;
    }

    //跳转到登陆页面
    @RequestMapping("/toLogin")
    public ModelAndView toLogin(HttpServletRequest request) {
    	HttpSession session = request.getSession();
        Object obj = session.getAttribute("currentUser");
        if (obj != null) {
            session.removeAttribute("currentUser");
        }
//    	User user = (User)session.getAttribute("currentUser");
//    	Object obj = session.getAttribute("user");
//    	if(obj != null) {
//    		System.out.println((Integer)obj);
//    	}
//    	if(user != null) {
//    		System.out.println(user.getUserName());
//    	}
        return new ModelAndView("user/login");
    }

    //登出
    @RequestMapping("/logout")
    public ModelAndView logout( HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if(session == null) {
            System.out.println("session is null");
        }
        session.removeAttribute("currentUser");
        session.removeAttribute("user");
        session.invalidate();
        return new ModelAndView("redirect:/user/toLogin");
    }


    //查所有
    @RequestMapping("/userList")
    public ModelAndView queryUserList(){
        ModelAndView model = new ModelAndView("user/userList");
        List<User> list =  userService.queryAllUser();
        model.addObject("userList", list);
        return model;
    }

    //跳转添加页面
    @RequestMapping("/addUserView")
    public ModelAndView addUserView(){
        ModelAndView model = new ModelAndView("user/addUser");
        return model;
    }

    //添加user
    @RequestMapping("/addUser")
    public ModelAndView addUser(User user){
        user.setBrith(new Date());
        user.setCreateTime(new Date());
        user.setLastLoginTime(new Date());
        userService.addUser(user);
        return new ModelAndView("redirect:/user/userList");
    }

    //跳转修改页面
    @RequestMapping("/updateUserView")
    public ModelAndView updateUserView(String userId){
        ModelAndView model = new ModelAndView("user/updateUser");
        User user = userService.queryUserByUserId(userId);
        model.addObject("user", user);
        return model;
    }

    //修改
    @RequestMapping("/updateUser")
    public ModelAndView updateUser(User user){
        userService.updateUser(user);
        return new ModelAndView("redirect:/user/userList");
    }

    //删除
    @RequestMapping("/deleteUser")
    public ModelAndView deleteUser(String userId){
        userService.deleteUser(userId);
        return new ModelAndView("redirect:/user/userList");
    }

    //查询登陆记录
    @RequestMapping("/queryLoginLog")
    public ModelAndView queryLoginLog(String userId){
        List<LoginLogVO> list = userLoginLogService.queryLoginLog(userId);
        ModelAndView mav = new ModelAndView("/user/lastLoginList");
        mav.addObject("userLoginList", list);
        return mav;
    }


    //获取头像
    @RequestMapping("/getImage")
    public void getImage(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
        User user = userService.queryUserByUserId(userId);
        String filePath;
        if (StringUtils.isEmpty(user.getImgUrl())) {
            filePath = "c:/1/1.png";
        } else {
            filePath = user.getImgUrl();
        }
        response.setContentType("image/png");
        OutputStream outputStream = response.getOutputStream();
        File file = new File(filePath);
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(file));
        ImageIO.write(bufferedImage, "png", outputStream);
        outputStream.flush();
        outputStream.close();
    }

    //上传文件
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    public String addPic(@RequestParam(value = "file", required = false) MultipartFile file , String userId) throws IOException {
        if (!file.isEmpty()) {
            String path = "c:/1/";
            // 获得原始文件名
            String fileName = file.getOriginalFilename();
            System.out.println("原始文件名:" + fileName);
            // 新文件名
            String newFileName = UUID.randomUUID() + "-" + fileName;
            System.out.println("新文件名:" + newFileName);
            try {
                FileOutputStream fos = new FileOutputStream(path + newFileName);
                InputStream in = file.getInputStream();
                int b;
                while ((b = in.read()) != -1) {
                    fos.write(b);
                }
                fos.close();
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
            User user = userService.queryUserByUserId(userId);
            user.setImgUrl(path + newFileName);
            userService.updateUser(user);
        }
        return "success";
    }





    private final static String getIpAddress(HttpServletRequest request)  {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }




}
